<template>
  <div class="graph-relation">
    <div class="u-graph" ref="graphRef" :style="{ backgroundColor }"></div>
    <Toolbar
      @clickZoomIn="clickZoomIn"
      @clickZoomOut="clickZoomOut"
      class="u-toolbar"
      v-if="showToolbar"
    ></Toolbar>
  </div>
</template>

<script setup name="GraphRelation">
import { onMounted, ref } from 'vue'
import Toolbar from './toolbar.vue'
import useResize from '../../../utils/resize'
import graphInit from '../../../shared/graph-relation/graphInit'

const props = defineProps({
  data: Object,
  limitLen: {
    type: Number,
    default: 6,
  },
  nodeVGap: {
    type: Number,
    default: 30,
  },
  nodeHGap: {
    type: Number,
    default: 30,
  },
  nodeWidth: {
    type: Number,
    default: 200,
  },
  defaultZoom: {
    type: Number,
    default: 0.7,
  },
  minZoom: {
    type: Number,
    default: 0.3,
  },
  maxZoom: {
    type: Number,
    default: 2,
  },
  mouseZoomable: {
    type: Boolean,
    default: true,
  },
  showToolbar: Boolean,
  backgroundColor: {
    type: String,
    default: '#F3F5F7',
  },
})

const emit = defineEmits(['clickLink', 'clickNode', 'clickToolbar'])


const graphRef = ref()
let graph = null

onMounted(() => {
  graph = graphInit({
    graphRef,
    data: props.data,
    defaultZoom: props.defaultZoom,
    minZoom: props.minZoom,
    maxZoom: props.maxZoom,
    mouseZoomable: props.mouseZoomable,
    limitLen: props.limitLen,
    nodeVGap: props.nodeVGap,
    nodeHGap: props.nodeHGap,
    nodeWidth: props.nodeWidth,
    clickLink(e, model) {
      emit('clickLink', model)
    },
    clickNode(e, model) {
      emit('clickNode', model)
    },
  })
})

useResize(() => graph.myResize())

function clickZoomIn() {
  graph.zoomTo(graph.getZoom() - 0.1, null, true)
  emit('clickToolbar', 'zoomIn')
}
function clickZoomOut() {
  graph.zoomTo(graph.getZoom() + 0.1, null, true)
  emit('clickToolbar', 'zoomOut')
}

defineExpose({
  getGraphInstance() {
    return graph
  },
})
</script>

<style lang="stylus" scoped>
.graph-relation
  position relative
  .u-graph
    width 100%
    height 100%
  .u-toolbar
    position absolute
    right 16px
    bottom 19px
</style>
